package com.zzyl.nursing.service.impl;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.zzyl.nursing.domain.NursingTask;
import com.zzyl.nursing.dto.NursingTaskDto;
import com.zzyl.nursing.dto.NursingTaskExecuteDto;
import com.zzyl.nursing.dto.NursingTaskUpdateTimeDto;
import com.zzyl.nursing.mapper.NursingTaskMapper;
import com.zzyl.nursing.service.INursingTaskService;
import com.zzyl.nursing.vo.NursingTaskVo;

@Slf4j
@Service
public class NursingTaskServiceImpl implements INursingTaskService{

    @Autowired
    private NursingTaskMapper nursingTaskMapper;

    @Override
    public List<NursingTask> list(NursingTaskDto dto) {
        List<NursingTask> list = nursingTaskMapper.list(dto);
        
        // 处理护理员姓名字符串转换为数组
        if (list != null) {
            for (NursingTask task : list) {
                if (StringUtils.hasText(task.getNursingNameStr())) {
                    // 将逗号分隔的字符串转换为List
                    List<String> nursingNameList = Arrays.stream(task.getNursingNameStr().split(","))
                            .map(String::trim)
                            .filter(name -> !name.isEmpty())
                            .collect(Collectors.toList());
                    task.setNursingName(nursingNameList);
                } else {
                    task.setNursingName(Collections.emptyList());
                }
            }
        }
        
        return list;
    }

    @Override
    public NursingTaskVo selectNursingTaskById(Integer id) {
        NursingTaskVo taskVo = nursingTaskMapper.selectNursingTaskById(id);
        
        // 处理护理员姓名字符串转换为数组
        if (taskVo != null && StringUtils.hasText(taskVo.getNursingNameStr())) {
            List<String> nursingNameList = Arrays.stream(taskVo.getNursingNameStr().split(","))
                    .map(String::trim)
                    .filter(name -> !name.isEmpty())
                    .collect(Collectors.toList());
            taskVo.setNursingName(nursingNameList);
        } else if (taskVo != null) {
            taskVo.setNursingName(Collections.emptyList());
        }
        
        return taskVo;
    }

    @Override
    public void cancel( String reason,
                       Integer taskId) {
        log.info("取消任务，任务ID：{}，取消原因：{}", taskId, reason);
        nursingTaskMapper.cancel(reason, taskId);
    }

    @Override
    public void execute(NursingTaskExecuteDto executeDto) {
        log.info("执行任务，任务ID：{}", executeDto.getTaskId());
        nursingTaskMapper.execute(executeDto);
    }

    @Override
    public void updateTime(NursingTaskUpdateTimeDto updateTimeDto) {
        log.info("更新任务时间，任务ID：{}", updateTimeDto.getTaskId());
        nursingTaskMapper.updateTime(updateTimeDto);
    }
}
